﻿using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Nuwanda.Common;
using Nuwanda.TfsSpotlight.Data;
using Nuwanda.TfsSpotlight.Shell;
using StructureMap;

namespace Nuwanda.TfsSpotlight.Views.Builds
{
    [Author("Bartłomiej Legiędź")]
    [Pluggable("BuildsView")]
    public partial class BuildsView : BaseUserControl, IBuildsView
    {
        private readonly Font _boldFont;
        private readonly ControlInvoker _invoker;

        public BuildsView()
        {
            InitializeComponent();

            this._invoker = new ControlInvoker(this);

            this.gvBuildData.RowPrePaint += this.RowPrePaintHandler;
            this._boldFont = new Font(this.gvBuildData.DefaultCellStyle.Font, FontStyle.Bold);
        }

        private void RowPrePaintHandler(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            var row = this.gvBuildData.Rows[e.RowIndex];
            var buildDataDescriptor = row.DataBoundItem as BuildDataDescriptor;
            if(buildDataDescriptor == null) return;

            row.DefaultCellStyle.Font = buildDataDescriptor.IsForCurrentUser ? this._boldFont : row.DefaultCellStyle.Font;
            row.DefaultCellStyle.BackColor = buildDataDescriptor.Color;
        }

        public List<BuildDataDescriptor> DataSource
        {
            set { SetDataSource(value); }
        }

        private void SetDataSource(List<BuildDataDescriptor> dataSource)
        {
            this._invoker.RunInControlsThread(() => this.bsBuildData.DataSource = dataSource);
        }

        public void StartProgress()
        {
            this._invoker.RunInControlsThread(() => this.pnlWorking.Visible = true);
        }

        public void StopProgress()
        {
            this._invoker.RunInControlsThread(() => this.pnlWorking.Visible = false);
        }

        public void Deselect()
        {
            this._invoker.RunInControlsThread(
                delegate
                    {
                        foreach (DataGridViewRow row in this.gvBuildData.SelectedRows)
                        {
                            row.Selected = false;
                        }
                    });
        }
    }
}